package com.example.demo.utils;

import cn.hutool.core.util.ObjectUtil;
import com.example.demo.base.config.auth.UserInfoShareHolder;
import com.example.demo.base.login.dto.UserCache;
import com.example.demo.enums.RoleEnum;
import com.example.demo.exception.ExceptionUtils;

import java.util.Optional;

public class RoleCheckUtils {

    private RoleCheckUtils() {
        throw new IllegalStateException("Utils");
    }

    public static boolean checkUser() {
        return valid(RoleEnum.USER);
    }

    public static boolean checkTrainer() {
        return valid(RoleEnum.TRAINER);
    }

    public static boolean checkAdmin() {
        return valid(RoleEnum.ADMIN);
    }

    @SuppressWarnings("all")
    public static boolean valid(RoleEnum role) {
        UserCache userInfo = Optional.ofNullable(UserInfoShareHolder.getUserInfo()).orElseThrow(() -> ExceptionUtils.exception("用户未登录"));
        if (userInfo == null) {
            throw ExceptionUtils.exception("用户未登录");
        }
        if (!ObjectUtil.equals(role.getIdentify(), userInfo.getUser().getRole())) {
            throw ExceptionUtils.exception("用户没有权限操作该功能");
        }
        return true;
    }

}
